package com.scd.encrypt.utils;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chengdu
 * @date 2018/10/22.
 */
public class AesUtil {

	private static final String UTF8ENCODE = "UTF-8";
	
	private static final String PKCS5_PADDING = "AES/ECB/PKCS5Padding";
	
	private static final String AG_AES = "AES";

    /**使用AES对字符串加密
     * @param str utf8编码的字符串
     * @param key 密钥（16字节）
     * @return 加密结果
     * @throws Exception
     */
    public static byte[] aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance(PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(UTF8ENCODE), AG_AES));
        byte[] bytes = cipher.doFinal(str.getBytes(UTF8ENCODE));
        return  bytes;
    }
    /**使用AES对数据解密
     * @param bytes utf8编码的二进制数据
     * @param key 密钥（16字节）
     * @return 解密结果
     * @throws Exception
     */
    public static String aesDecrypt(byte[] bytes, String key) throws Exception {
        if (bytes == null || key == null) return null;
        Cipher cipher = Cipher.getInstance(PKCS5_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(UTF8ENCODE), AG_AES));
        bytes = cipher.doFinal(bytes);
        return new String(bytes, UTF8ENCODE);
    }

    public static void main(String[] args) throws Exception {
    	String msg = "aaa成都";
    	String key = "1111111111111111";
    	System.out.println(key.length());
    	
    	byte[] aesMsg = aesEncrypt(msg, key);
    	// 转换成 Base64 传输
    	String saesMsg = Base64Util.encryptBASE64(aesMsg);
    	
    	// 传输到指定服务器使用  AES 解密
    	byte[] daesMsg = Base64Util.decryptBASE64(saesMsg);
    	System.out.println(aesDecrypt(daesMsg, key));
    	
    	
    	String imgpath = "C:/Users/chengdu/Desktop/encrypt/" + "geo.PNG";
    	String picBase64 = Base64Util.getPicBASE64(imgpath);
    	// 对 picBase64图片加密
    	byte[] aesPic = aesEncrypt(picBase64, key);
    	// 转成Base64字符串传输
    	String aesStr = Base64Util.encryptBASE64(aesPic);
    	
    	// aes解密
    	byte[] dePIc = Base64Util.decryptBASE64(aesStr);
    	String dePicData = aesDecrypt(dePIc, key);
    	String outPath = "C:/Users/chengdu/Desktop/encrypt/" + "geoaaa.png";
    	Base64Util.formatBASE64Img(dePicData, outPath);
    }
}

